package me.zhengjie.tool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * Created by TQ ThinkPad on 2020/5/8.
 */
public class MachineUtil {

    private static final Logger log = LoggerFactory.getLogger(MachineUtil.class);

    /**
     * 获取本机ip
     * @return
     */
    public static String getIp() {
        String sIP = "";
        InetAddress ip = null;
        try {
            boolean bFindIP = false;
            Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
            while (netInterfaces.hasMoreElements()) {
                if (bFindIP) {
                    break;
                }
                NetworkInterface ni = netInterfaces.nextElement();
                Enumeration<InetAddress> ips = ni.getInetAddresses();
                while (ips.hasMoreElements()) {
                    ip = ips.nextElement();
                    if (!ip.isLoopbackAddress()
                            && ip.getHostAddress().matches("(\\d{1,3}\\.){3}\\d{1,3}")) {
                        bFindIP = true;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            LogUtil.error(e);
        }
        if (null != ip) {
            sIP = ip.getHostAddress();
        }
        return sIP;
    }

    /**
     * 获取机器名称
     * @return
     */
    public static String getName () {
        InetAddress addr = null;
        String name = "";
        try {
            addr = InetAddress.getLocalHost();
            name = addr.getHostName();
        } catch (Exception e) {
            return name;
        }
        return name;
    }


    /**
     * 获取mac地址
     * @return
     */
    public static String getMACAddress(){
        InetAddress ia = null;
        StringBuffer sb = new StringBuffer();
        try {
            ia = InetAddress.getLocalHost();
            //获得网络接口对象（即网卡），并得到mac地址，mac地址存在于一个byte数组中。
            byte[] mac = NetworkInterface.getByInetAddress(ia).getHardwareAddress();
            for(int i=0;i<mac.length;i++){
                if(i!=0){
                    sb.append("-");
                }
                //mac[i] & 0xFF 是为了把byte转化为正整数
                String s = Integer.toHexString(mac[i] & 0xFF);
                sb.append(s.length()==1?0+s:s);
            }
        } catch (Exception e) {
            return "";
        }

        //把字符串所有小写字母改为大写成为正规的mac地址并返回
        return sb.toString().toUpperCase();
    }

}
